package com.pactera.jep.service.sys.web.controller;

import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.model.DictItem;
import com.pactera.jep.sys.service.DictCateService;
import com.pactera.jep.sys.service.DictItemService;
import com.pactera.jep.sys.service.DictService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.BasicNameValuePair;
import com.pactera.jep.web.entity.NameValuePair;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "字典项管理")
@RestController
@RequestMapping("/dictItem")
public class DictItemRestController extends BaseRestController<DictItem> {
    Logger logger	= LoggerFactory.getLogger(DictItemRestController.class);

    @Autowired
    DictItemService dictItemService;

    @Autowired
    DictService dictService;

    @Autowired
    DictCateService dictCateService;

    /**
     * 为列表页面做数据准备
     */
    @Override
    protected void prepareQuery(@ApiIgnore @RequestHeader("x-user-token") String token, Page<DictItem> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
        dictItemService.query(page, filters, orders);
    }

    /**
     * 保存
     * @param dictItem
     * @return
     */
    @ApiOperation(value = "保存一条数据")
    @PostMapping(value = "/save")
    public Map<String, Object> save(@RequestBody DictItem dictItem) {

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            if(StringUtils.isEmpty(dictItem.getItemId()))
            {
                dictItemService.insert(dictItem);
            }
            else
            {
                dictItemService.update(dictItem);
            }
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
        }
        catch (ServiceException e)
        {
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
        }

        return tips;
    }

    /**
     * 删除
     * @param itemId
     * @return
     */
    @ApiOperation(value = "根据id删除一条数据")
    @PostMapping(value = "/remove/{itemId}")
    public Map<String, Object> remove(@PathVariable String itemId){

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            dictItemService.deleteByPrimaryKey(itemId);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        }
        catch (ServiceException e)
        {
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
        }

        return tips;
    }

    /**
     * 验证提交的itemId是否已经存在数据库中
     * @param itemId
     * @return
     */
    @ApiOperation(value = "验证提交的编码是否已经存在数据库中")
    @GetMapping(value = "/check", produces = "application/json;charset=UTF-8")
    public Map<String, Object> check(String itemId){

        Map<String, Object> tips = new HashMap<String, Object>();

        DictItem exist = dictItemService.get(itemId);
        if(exist == null)
        {
            tips.put("valid", true);
        }
        else
        {
            tips.put("valid", false);
        }
        return tips;
    }

    /**
     * 根据字典编码 查询字典
     * @param simpleName
     * @param excludes
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDictItems/{simpleName}")
    @ResponseBody
    public List<NameValuePair> getDictItems(@PathVariable String simpleName, @RequestParam(value = "excludes", required = false) String excludes) throws Exception {
        List<NameValuePair> items = new ArrayList<>();

        try
        {

            List<Filter> filters = new Filter.Builder().eq("dictCode", simpleName).build();
            List<DictItem> list = dictItemService.select(filters);

            //过滤掉不要的字典项
            if(!CollectionUtils.isEmpty(list))
            {
                for(int i = 0; i < list.size(); i++)
                {
                    DictItem item = list.get(i);
                    if(org.springframework.util.StringUtils.hasText(excludes) && excludes.contains(item.getItemValue())) continue;
                    BasicNameValuePair nv = new BasicNameValuePair(item.getItemLabel(), item.getItemValue());
                    items.add(nv);
                }
            }

            return items;
        } catch (ServiceException se) {
            logger.error("系统出现异常：" + se.getMessage());
            throw se;
        }
    }
}
